import {useEffect, useRef, useState} from 'react'
import {CommonEnum} from '@/enums'

import {isEmpty} from 'project-libs'
import {useObserverHook} from './index'


export default function useHttpHook({
                                      func, resetFunc, searchFunc
                                    }) {
  const [ page, setPage ] = useState(CommonEnum.PAGE)

  const [ data, setData ] = useState([])

  const [ showLoading, setShowLoading ] = useState(true)

  const [ loading, setLoading ] = useState(false)

  const searchData = useRef({})

  const invokeHttp = async ({pageIndex = 0} = {}) => {
    const result = await func({
      ...page,
      pageIndex,
      ...searchData.current
    })
    return result
  }

  const getData = async () => {
    setLoading(true)
    const result = await invokeHttp()
    if (result.length <= page.pageSize) {
      setData(result)
      setShowLoading(true)
    } else {
      setShowLoading(false)
    }
    setLoading(false)
  }

  useObserverHook('#' + CommonEnum.LOADING_ID, async (entries) => {
    if (entries[0].isIntersecting && !loading) {
      const result = await invokeHttp({pageIndex: page.pageIndex + 1})
      if (!isEmpty(result) && !isEmpty(data) && result.length <= page.pageSize) {
        setPage({
          ...page,
          pageIndex: page.pageIndex + 1
        })
        // 如果结果长度小于分页尺寸，则不分页
        if (result.length < page.pageSize) {
          setShowLoading(false)
        } else {
          // 继续分页
          setShowLoading(true)
        }
        setData([ ...data, ...result ])
      } else {
        // 停止分页
        setShowLoading(false)
      }
    }
  }, null)

  const reset = () => {
    setPage(CommonEnum.PAGE)
    searchData.current = {}
    getData()
  }

  const onSearch = (data) => {
    searchData.current = data
    setPage(CommonEnum.PAGE)
    getData()
  }

  resetFunc && resetFunc(reset)

  searchFunc && searchFunc(onSearch)

  useEffect(() => {
    getData()
  }, [])

  return {data, loading, showLoading}
}
